﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MillsClient;
using MillsClientGameForm;
using System.Threading;

namespace ClientMainWindow
{
    public partial class MillsBeforeGameForm : Form
    {
        AsynchronoiusIOClient _millsClientObj = null;
        Thread threadWiating;
        string recieveMessage = string.Empty;

        public MillsBeforeGameForm()
        {
            InitializeComponent();
        }
        public MillsBeforeGameForm(ref AsynchronoiusIOClient client, string name)
        {
            InitializeComponent();
            lbYourName.Text = name;
            _millsClientObj = client;
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            string message = @"ready\EOM";

            _millsClientObj.Send(message);
            Logger.WriteLog(string.Format("Send: {0}", message));
            
            threadWiating = new Thread(new ThreadStart(Waiting));
            threadWiating.IsBackground = true;
            threadWiating.Start();
            //this.Enabled = true;
            btnPlay.Enabled = false;       
        }

        //Делегат и функция, для изменения свойств кнопки в другом потоке.
        delegate void BtnStateChangeDelegate(Button btn, bool flag);
        void BtnStateChange(Button btn, bool flag)
        { 
            if (InvokeRequired)
            {
                BeginInvoke(new BtnStateChangeDelegate(BtnStateChange), new object[] { btn, flag});
                return;
            }
            else
            {
                if (flag)
                {
                    btn.Enabled = false;
                    btn.Text = "Ожидание оппонента";
                }
                else
                {
                    btn.Text = "Играть";
                    btn.Enabled = true;
                }
            }
        }
        //Делегат и функция для запуска окна игры
        delegate void newForm(bool b, string s1, string s2);
        void newF(bool b, string s1, string s2)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new newForm(newF), new object[] { b, s1, s2 });
                return;
            }
            else
            {
                MillsClientForm mcf = new MillsClientForm(ref _millsClientObj, b, s1, s2);
                this.Visible = false;
                DialogResult result = mcf.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.Cancel)
                {
                    this.Visible = true;
                }
            }
        }

        private bool MessageParsing(string Message)
        {
            bool leader;
            bool flag = true;
            string you = lbYourName.Text;
            string opponent = string.Empty;
            if (recieveMessage.Contains("lead="))
            {
                if (recieveMessage.Contains("true"))
                    leader = true;
                else
                    leader = false;
                opponent = recieveMessage.Substring(recieveMessage.IndexOf(' '), recieveMessage.Length - recieveMessage.IndexOf(' '));
                //Запуск игры.
                newF(leader, you, opponent);
                return true;
            }
            if (recieveMessage == @"denied\EOM")
            {
                MessageBox.Show("Поиграть не получится");
                BtnStateChange(btnPlay, false);
                return true;
            }
            else
            {
                Logger.WriteLog("Unknown error");
                flag = false;
            }
            return flag;
        }

        private void Waiting()
        {            
            while (true)
            {
                recieveMessage = _millsClientObj.ConnectionInformation.recieveBuffer;
                if (recieveMessage != string.Empty)
                {
                    if (recieveMessage == @"searching for an opponent for you...\EOM")
                    {
                        BtnStateChange(btnPlay, true);
                    }
                    else
                    {
                        Logger.WriteLog(string.Format("Rec: {0}", recieveMessage));
                        if (MessageParsing(recieveMessage))
                            break;
                    }
                    recieveMessage = string.Empty;
                }
            }
            this.threadWiating.Abort();
        }

        private void btnStatistics_Click(object sender, EventArgs e)
        {
            this.Size = this.MaximumSize;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MillsBeforeGameForm_Load(object sender, EventArgs e)
        {
            _millsClientObj.Recieve();
            tssMessage.Text = Encoding.ASCII.GetString(_millsClientObj.ConnectionInformation.Buffer);
        }

        private void MillsBeforeGameForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(this.DialogResult != System.Windows.Forms.DialogResult.Cancel)
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            if (threadWiating != null)
                threadWiating.Abort();
        }

        private void btnLogOff_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
            this.Dispose();
        }
    }
}
